/**
 * Created by zhouli on 18/9/8
 * Email li.zhou@huilianyi.com
 */
//新增自定义值列表
import React from 'react';
import {connect} from 'react-redux';
import {Button, Form, Input, Col, Row, Switch, Icon, message} from 'antd';
import CVIDService from 'containers/setting/value-list/custom-value-item-detail/custom-value-item-detail.service';
import 'styles/setting/value-list/custom-value-item-detail/new-custom-value-item.scss';
import {LanguageInput} from 'components/index';
import {deepCopy, messages} from "share/common";
import menuRoute from 'routes/menuRoute';
const FormItem = Form.Item;
import {valueListItemDefault} from "containers/setting/value-list/value-list.model";
class NewCustomValueItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      valueListItemDetail: deepCopy(valueListItemDefault),
      customValueItemDetailPath: menuRoute.getRouteItem("custom-value-item-detail"),
    };
  }

  componentDidMount() {
    if (this.props.params.customValueItemOID === "NEW") {
      //新增
    } else {
      //更新
      this.getCustomValueItemDetail()
    }
  }

  //查看成本中心项详情
  getCustomValueItemDetail() {
    CVIDService.getDetailValueListItem(this.props.params.customValueItemOID)
      .then((response) => {
        let data = response.data;
        this.setState({
          valueListItemDetail: data,
        })
      });
  }


  //成本中心项详情
  customValueItemDetail = (record) => {
    let url = this.state.customValueItemDetailPath.url;
    let path = url.replace(":customValueItemOID", record.customEnumerationItemOID);
    let _path = path.replace(":customEnumerationOID", this.props.params.customEnumerationOID);
    let __path = _path.replace(":customEnumerationID", this.props.params.customEnumerationID);
    this.context.router.push(__path);
  };

  validateMessageKeyLengthErr = (messageKey) => {
    if (messageKey === null || messageKey === undefined || messageKey === "") {
      message.warn(messages('setting.key336'/*请填写名称*/));
      return true;
    }
    if (messageKey && messageKey.length && messageKey.length > 300) {
      //需求 4759 长度修改为300
      message.warn(messages('setting.key1794')/*名称最多输入300个字符*/);
      return true;
    }
  }


  handleSave = (e) => {
    e.preventDefault();
    let valueListItemDetail = this.state.valueListItemDetail;
    valueListItemDetail.customEnumerationOID = this.props.params.customEnumerationOID;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        //名称涉及到多语言，就不用values
        values.name = valueListItemDetail.name;
        valueListItemDetail = Object.assign(valueListItemDetail, values);
        if (this.validateMessageKeyLengthErr(valueListItemDetail.messageKey)) {
          return
        }
        if (valueListItemDetail.id) {
          this.updateValueListItem(valueListItemDetail);
        } else {
          this.createValueListItem(valueListItemDetail);
        }
      }
    });
  };
  createValueListItem = (valueListItem) => {
    this.setState({
      loading: true,
    });
    CVIDService.createValueListItem(valueListItem)
      .then((res) => {
        if (res) {
          this.setState({loading: false});
          this.customValueItemDetail(res.data)
        }
      })
      .catch(() => {
        this.setState({loading: false});
      })
  }
  updateValueListItem = (valueListItem) => {
    this.setState({
      loading: true,
    });
    CVIDService.updateValueListItem(valueListItem)
      .then((response) => {
        if (response) {
          this.setState({loading: false});
          this.context.router.goBack();
        }
      })
      .catch(() => {
        this.setState({loading: false});
      })
  }
  //点击取消，返回
  handleCancel = (e) => {
    e.preventDefault();
    this.context.router.goBack();
  };
  //名称：自定义值列表项多语言
  i18nNameChange = (name, i18nName) => {
    this.state.valueListItemDetail.messageKey = name;
    if (this.state.valueListItemDetail.i18n) {
      this.state.valueListItemDetail.i18n.messageKey = i18nName;
    } else {
      this.state.valueListItemDetail.i18n = {
        messageKey: i18nName
      };
    }
  }

  handleChange = (val) => {
    if (this.state.loading) {
      this.setState({
        loading: false
      })
    }
  };

  // -----编辑状态---end
  render() {
    const {getFieldDecorator} = this.props.form;
    const {loading, valueListItemDetail} = this.state;
    return (
      <div className="new-cost-center-item">
        <Form onSubmit={this.handleSave} onChange={this.handleChange}>
          <Row gutter={24} className="cost-center-form-row">
            <Col span={8}>
              <FormItem
                label={messages('setting.key1224'/*编码*/)}
                colon={true}>
                {getFieldDecorator('value', {
                  initialValue: valueListItemDetail.value,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                    {
                      max: 100,
                      message: messages('setting.key343'/*最多输入100个字符*/),
                    },
                  ]
                })(
                  <Input disabled={valueListItemDetail.id} placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label={messages('setting.key1225'/*值名称*/)}>
                {getFieldDecorator('messageKey', {
                  initialValue: valueListItemDetail.messageKey,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    }],
                })(
                  <div>
                    <LanguageInput
                      name={valueListItemDetail ? valueListItemDetail.messageKey : ""}
                      i18nName={valueListItemDetail && valueListItemDetail.i18n &&
                      valueListItemDetail.i18n.messageKey ? valueListItemDetail.i18n.messageKey : null}
                      isEdit={valueListItemDetail && valueListItemDetail.id}
                      nameChange={this.i18nNameChange}
                    />
                  </div>
                )}
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages('setting.key344'/*序号*/)}
                colon={true}>
                {getFieldDecorator('sequenceNumber', {
                  initialValue: valueListItemDetail.sequenceNumber,
                  rules: [
                    {
                      message: messages('setting.key1448'/*请输入正整数*/),
                      validator: (rule, value, cb) => {
                        if (value === null || value === undefined || value === "") {
                          cb();
                          return;
                        }
                        //去掉空格
                        value = value.replace(/ /g, '');
                        if (value.split(".").length > 1) {
                          cb(false);
                        } else {
                          cb();
                        }
                      },
                    },
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>
              <div className="cost-center-index-tip"> {messages('setting.key1663')/*按照序号由小到大排序，不填默认为999。序号之间尽量保持一定的步长，便于后续调整，如首位10，间隔10。*/}
              </div>
            </Col>

          </Row>


          <Row gutter={24} className="cost-center-form-row">

            <Col span={8}>
              <FormItem
                label={messages('common.remark')}
                colon={true}>
                {getFieldDecorator('remark', {
                  initialValue: valueListItemDetail.remark,
                  rules: [
                    {
                      max: 200,
                      message: messages('setting.key1226'/*最多输入200个字符*/),
                    },
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages('setting.key350'/*全员可见*/)}
                colon={false}>
                {getFieldDecorator("common", {
                  initialValue: valueListItemDetail.common,
                  valuePropName: 'checked',
                  rules: [],
                })
                (<Switch checkedChildren={<Icon type="check"/>}
                         unCheckedChildren={<Icon type="cross"/>}/>)
                }
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages("common.status", {status: ""})}
                colon={true}>
                {getFieldDecorator("enabled", {
                  initialValue: valueListItemDetail.enabled,
                  valuePropName: 'checked',
                  rules: [],
                })
                (<Switch checkedChildren={<Icon type="check"/>}
                         unCheckedChildren={<Icon type="cross"/>}/>)
                }
              </FormItem>
            </Col>
          </Row>

          <Button type="primary" loading={loading} htmlType="submit">
            {messages("common.save")}
          </Button>
          <Button onClick={this.handleCancel} style={{marginLeft: 8}}>
            {messages("common.cancel")}
          </Button>

        </Form>
      </div>
    )
  }
}

NewCustomValueItem.contextTypes = {
  router: React.PropTypes.object
};
function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  }
}
const WrappedNewCustomValueItem = Form.create()(NewCustomValueItem);
export default connect(mapStateToProps)(WrappedNewCustomValueItem);
